package com.chunxuan.langquan.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.blankj.utilcode.util.RegexUtils;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.LqProvinceBean;
import com.chunxuan.langquan.dao.bean.ReceiptAddressInfo;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.view.JDCityPicker;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class EditAddressActivity extends Base2Activity {

    private AppCompatEditText etReceiver,etMobile,etDetailAddress;
    private TextView tvConfirm,tvDelete;
    private AppCompatTextView tvArea;
    private ImageView ivBack;
    private ReceiptAddressInfo receiptAddressInfo;
    private JDCityPicker mJDCityPicker;
    private List<LqProvinceBean> lqProvinceBeanList=new ArrayList<>();
    private int mProvinceId, mCityId, mAreaId;
    private boolean areaSelected=false;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_address_edit;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        etReceiver=findViewById(R.id.et_receiver);
        etMobile=findViewById(R.id.et_mobile);
        etDetailAddress=findViewById(R.id.et_detail_address);
        tvConfirm=findViewById(R.id.tv_confirm);
        tvDelete=findViewById(R.id.tv_delete);
        tvArea=findViewById(R.id.et_delivery_address_area_input);
        ivBack=findViewById(R.id.iv_back);
        Intent intent=getIntent();
        if(null!=intent){
            Bundle bundle = intent.getExtras();
            receiptAddressInfo= (ReceiptAddressInfo) bundle.getSerializable("receiptAddressInfo");
            if(null!=receiptAddressInfo){
                etReceiver.setText(receiptAddressInfo.getName());
                etMobile.setText(receiptAddressInfo.getMobile());
                tvArea.setText(receiptAddressInfo.getProvince_name()+"-"+receiptAddressInfo.getCity_name()+"-"+receiptAddressInfo.getArea_name());
                etDetailAddress.setText(receiptAddressInfo.getAddress());
            }
        }
        getProvList();
        setOnClickListener(ivBack,tvConfirm,tvDelete,tvArea);
    }
    private Disposable getProvList() {
        return APIRetrofit.getDefault().getProvList(Global.HEADER,"")
                .compose(RxUtil.<BaseResult2<List<LqProvinceBean>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<LqProvinceBean>>>() {
                    @Override
                    public void accept(BaseResult2<List<LqProvinceBean>> result2) throws Exception {
                        hideProgress();
                        if(result2.isSuccess()){
                            lqProvinceBeanList=result2.getData();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取省份列表失败");
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_confirm:
                if(!RegexUtils.isMobileExact(etMobile.getText().toString().trim())){
                    ToastUtils.showShort("请填写正确的手机号");
                    return;
                }
                if(!areaSelected){
                    confirmAddress(receiptAddressInfo.getId(),etReceiver.getText().toString().trim(),etMobile.getText().toString().trim(),
                            receiptAddressInfo.getProvince_id(),receiptAddressInfo.getCity_id(),receiptAddressInfo.getArea_id(),
                            etDetailAddress.getText().toString().trim(),receiptAddressInfo.getIs_default());
                }else{
                    confirmAddress(receiptAddressInfo.getId(),etReceiver.getText().toString().trim(),etMobile.getText().toString().trim(),
                            mProvinceId,mCityId,mAreaId,etDetailAddress.getText().toString().trim(),receiptAddressInfo.getIs_default());
                }
                break;
            case R.id.tv_delete:
                deleteAddress(receiptAddressInfo.getId());
                break;
            case R.id.et_delivery_address_area_input:
                bgAlpha(0.7f);
                mJDCityPicker = new JDCityPicker(EditAddressActivity.this,lqProvinceBeanList, new JDCityPicker.onCitySelect() {
                    @Override
                    public void onSelect(String province, String city, String area,int province_id,int city_id,int area_id) {
                        tvArea.setText(province + "-" + city + "-" + area);
                        mProvinceId=province_id;
                        mCityId=city_id;
                        mAreaId=area_id;
                        areaSelected=true;
                    }
                },"","","");
                mJDCityPicker.showAtLocation(tvArea, Gravity.BOTTOM, 0, 0);

                mJDCityPicker.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        bgAlpha(1.0f);
                    }
                });
                break;
        }
    }
    //背景变暗
    private void bgAlpha(float f) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = f;
        getWindow().setAttributes(layoutParams);
    }

    private Disposable deleteAddress(int id) {
        return APIRetrofit.getDefault().deleteAddress(Global.HEADER,id)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        if(result2.isSuccess()){
                            ToastUtils.showShort(result2.getMsg());
                            finish();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("删除收货地址失败");
                    }
                });
    }

    /**
     * @param id 收货地址id
     * @param name
     * @param mobile
     * @param province_id
     * @param city_id
     * @param area_id
     * @param address
     * @param is_default 是否默认 1-是 0-否
     * @return
     */
    private Disposable confirmAddress(int id, String name, String mobile, int province_id, int city_id, int area_id, String address, int is_default) {
        return APIRetrofit.getDefault().confirmAddress(Global.HEADER,id, name, mobile, province_id,
        city_id, area_id, address, is_default)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        if(result2.isSuccess()){
                            ToastUtils.showShort(result2.getMsg());
                            finish();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("确认收货地址失败");
                    }
                });
    }
}
